<?php
	namespace Home\Controller;
	use Think\Controller;
	use \Model\UserModel;
class UserController extends Controller {
    public function login(){
    	if(!empty($_POST)){
			$user=new \Model\UserModel();
				$info=$user->check($_POST['name'],$_POST['password']);
				if($info){
					if($info['status']==1){//判断账号是否被冻结
						echo "<script>alert('登录成功！')</script>";
						//给用户信息session持久化操作
						session('name',$info['name']);
						session('id',$info['id']);
						session('touxiang',$info['touxiang']);
						//页面跳转到后台
						$this->redirect('Index/index');
					}else{
						echo "<script>alert('账号已被冻结！')</script>";
					}
				}else{
					echo "<script>alert('用户名或密码错误！')</script>";
					//$this->redireclt('index/index');
				}
		}			
		$this->display('Index/index');
    }
	public function register(){
		if(!empty($_POST)){
				if($_FILES['touxiang']['error']==0&&$_POST['name']!=''&&$_POST['password']!=''
				&&$_POST['email']!=''&&$_POST['phone']!=''&&$_POST['sex']!=''){										
					if($this->is_used($_POST['name'])){
						//echo "<script>alert('可以')</script>";
						$new_user=new \Model\UserModel();						
						$cfg=array('rootPath'      => './upload/');
						$up=new \Think\Upload($cfg);
						$upload_result=$up->uploadOne($_FILES['touxiang']);
						//图片路径
						$pic_path=$up->rootPath.$upload_result['savepath'].$upload_result['savename'];
						$_POST['touxiang']=ltrim($pic_path,'.');
						$_POST['create_time']=$_SERVER['REQUEST_TIME'];
						//dump($_POST);
							if($new_user->add($_POST)){
								echo "<script>alert('注册成功！')</script>";
								$this->redirect('Index/index',array(),1,'');
							}else{
								echo "<script>alert('注册失败！')</script>";
								$this->redirect('User/register');
							}
						
					}else{
						echo "<script>alert('都说了用户名被使用了--')</script>";
					}
				 //dump($_FILES);
				}
				else{					
					echo "<script>alert('还有信息尚未填写！')</script>";
				}
			}
		$this->display();
	}
	
	function is_used($name){
		$info=D('user')->where("name ='$name'")->find();
		if($info===null){
			echo "true";			
			return true;
		}else{
			echo "false";
			return false;
		}
		
	}
	function is_used_name($name){
		$info=D('user')->where("name ='$name'")->find();
		if($info===null){
			echo "<span style='color:green'>恭喜用户名可以使用！^_^</span>";
			return true;
		}else{
			echo "<span style='color:red'>此用户已被注册T_T</span>";
			return false;
		}
		exit;
	}
	function index(){
		//echo urlencode("http://192.168.43.59/index.php/Home/User/index");
		//var_dump(session());exit;
		//需要先验证登录状态，没登录则跳转至登录界面
		$pc=new \Tools\PublicController();
		$my=$pc->require_login();
		$info=array();
		//查找各种状态的订单数量
		$waitsend=D('goods_order')->where("user_id=".$my['id']." and status=".\Model\OrderModel::WAIT_SEND)->count();
//		var_dump($waitsend);
		$waitreceive=D('goods_order')->where("user_id=".$my['id']." and status=".\Model\OrderModel::WAIT_RECEIVE)->count();
		$waitcomment=D('goods_order')->where("user_id=".$my['id']." and status=".\Model\OrderModel::WAIT_COMMENT)->count();
		$waitrefund=D('goods_order')->where("user_id=".$my['id']." and status=".\Model\OrderModel::WAIT_REFUND)->count();
		$info['orderstatuscount']=array("waitsend"=>$waitsend,"waitreceive"=>$waitreceive,"waitcomment"=>$waitcomment,"waitrefund"=>$waitrefund);
		//查找用户收藏数
		$goods_fav_count=D('goods_fav')->where("user_uid=".$my['id'])->count();
		//查找购物车记录条数
		$goods_cart_count=D('goods_cart')->where("user_uid=".$my['id'])->count();
		//地址条数
		$address_count=D('address')->where("user_id=".$my['id'])->count();
		//查找订单条数
		$goods_order_count=D('goods_order')->where("user_id=".$my['id'])->count();
		$info['goods_fav_count']=$goods_fav_count;
		$info['goods_cart_count']=$goods_cart_count;
		$info['address_count']=$address_count;
		$info['goods_order_count']=$goods_order_count;
//		var_dump($info);
		$this->assign('info',$info);
		$this->assign('my',$my);
		$this->display();
	}
	
	function loginout(){
		if(!empty($_SERVER["REMOTE_ADDR"])){
		     $ip = $_SERVER["REMOTE_ADDR"];
		    }
		//var_dump($_SERVER);
		$last_time=$_SERVER['REQUEST_TIME'];
		$sql="update user set last_time=".$last_time.",last_ip='".$ip."' where id=".session('id').";";
		//echo $sql;
		session(null);//清空session
		$this->redirect('User/index');
	}
	//积分商城登录
	public function integrallogin(){
    	if(!empty($_POST)){
    		//echo "用户名";exit;
			$user=new \Model\UserModel();
				$info=$user->check($_POST['name'],$_POST['password']);
				if($info){
					if($info['status']==1){//判断账号是否被冻结
						//echo "<script>alert('登录成功！')</script>";
//						$this->ajaxReturn("1");
						//给用户信息session持久化操作
						session('name',$info['name']);
						session('id',$info['id']);
						//页面跳转到后台
//						$this->redirect('IntegralGoods/goalstore');
						$this->ajaxReturn(array("error"=>0,"tip"=>"登录成功"));
					}else{
						$this->ajaxReturn(array("error"=>1,"tip"=>"账号已被冻结！"));
//						echo "账号已被冻结！";exit;
					}
				}else{
					$this->ajaxReturn(array("error"=>1,"tip"=>"用户名或密码错误！"));
//					echo "用户名或密码错误！";exit;
					//$this->redireclt('index/index');
				}
		}			
		$this->display();
    }
	function address(){//地址列表
		$address=D('address')->where('user_id='.session('id'))->select();
//		var_dump($address);
		$this->assign('address',$address);
		$this->display();
	}
	function addaddress($userid){//添加地址
		if(!empty($_POST)){
			$_POST['user_id']=$userid;
//			var_dump($_POST);
			$address_model=new \Model\AddressModel();
			if($address_model->add($_POST)){
				$this->redirect('User/address');
			}else{
				echo "<script>alert('添加失败')</script>";
				$this->redirect('User/address',array(),1," ");
			}
		}else{
			$provinces=D('provinces')->select();
	//		var_dump($provinces);exit;
			$this->assign('provinces',$provinces);
			$this->display();
		}
	}
	function editaddress($uid){//编辑地址
		if(!empty($_POST)){
//			var_dump($_POST);
			$_POST['uid']=$uid;
			$address_model=new \Model\AddressModel();
			if($address_model->save($_POST)){
				$this->redirect('User/address');
			}else{
				echo "<script>alert('修改失败或没做修改')</script>";
				$this->redirect('User/address',array(),1," ");
			}
		}else{
			$provinces=D('provinces')->select();
	//		var_dump($provinces);exit;
			$address=D('address')->where('uid='.$uid)->find();
//			var_dump($address);
			$this->assign('address',$address);
			$this->assign('provinces',$provinces);
			$this->display();
		}
	}
	//删除地址
	function deleteaddress($uid){
		$res=D('address')->where("uid=".$uid)->delete();
		if($res){
//				echo "<script>location.href='".$_SERVER["HTTP_REFERER"]."';</script>";
				$this->redirect('User/address');
			}else{
				echo "<script>alert('删除失败')</script>";
				$this->redirect('User/address',array(),1," ");
			}
	}
	function getcity($provinceid){//三级联动时获取城市
		$citys=D('cities')->where('provinceid='.$provinceid)->select();
		$this->ajaxReturn($citys);
//		var_dump($citys);
	}
	function getarea($cityid){//三级联动时获取区县
		$areas=D('areas')->where('cityid='.$cityid)->select();
		$this->ajaxReturn($areas);
//		var_dump($citys);
	}
	function setfirstaddress($uid=0,$tochangeuid){//设置为默认地址
		//echo $uid;echo "</br>";echo $tochangeuid;
		$db=new \Model\DbModel();
		$db->startTrans();
		$res2=1;
		$res=$db->updatedata("address",array("first"=>"1"),"uid=".$tochangeuid);
		if($uid){//当已经设置了默认地址的时候会执行这里
			$res2=$db->updatedata("address",array("first"=>"0"),"uid=".$uid);
		}
		if($res&&$res2){
			$db->commit();
			$this->ajaxReturn(1);
		}else{
			$db->rollback();
			$this->ajaxReturn(0);
		}
	}
	//收藏列表
	function favlist(){
		$sql="select g.* from goods_fav as f,integralgoods as g where f.goods_uid=g.id and f.user_uid=".session('id');
		$favgoods=D('integralgoods')->query($sql);
//		var_dump($favgoods);
		$this->assign('favgoods',$favgoods);
		$this->display();
	}
	//删除收藏商品
	function deletefav($id){
		//删除收藏记录并减少商品收藏数
		D('goods_fav')->where('goods_uid='.$id." and user_uid=".session('id'))->delete()&&D('integralgoods')->execute("update integralgoods set fav_cnt=fav_cnt-1 where id=".$id)?$this->ajaxReturn(1):$this->ajaxReturn(0);
	}
	//购物车列表
	function shopcartlist(){
		//需要先验证登录状态，没登录则跳转至登录界面
		$pc=new \Tools\PublicController();
		$my=$pc->require_login();
//		$shopcartlist=D('goods_cart')->where('user_uid='.session('id'))->select();
		$sql="select i.*,g.quantity from integralgoods as i,goods_cart as g where i.id=g.goods_uid and g.user_uid=".session('id');
		$shopcartlist=D('goods_cart')->query($sql);
//		var_dump($shopcartlist);
		$this->assign('shopcartlist',$shopcartlist);
		$this->display();
	}
	//删除购物车商品
	function deleteshopcart($id){
		
		D('goods_cart')->where('goods_uid='.$id." and user_uid=".session('id'))->delete()?$this->ajaxReturn(1):$this->ajaxReturn(0);
	}
	//展示和修改注册信息
	function registerinfo(){
		if(!empty($_POST)){
			$_POST['id']=session('id');
			//上传新头像
				$cfg=array('rootPath'      => './upload/');
				$up=new \Think\Upload($cfg);
				if($_FILES['touxiang']['error']!=4){//判断是否上传了图片,不上传则不修改图片
					$upload_result=$up->uploadOne($_FILES['touxiang']);
					//图片路径
					$pic_path=$up->rootPath.$upload_result['savepath'].$upload_result['savename'];
					//修改为新的图片路径
					$_POST['touxiang']=ltrim($pic_path,'.');
				}
//					var_dump($_POST);
					if(D('user')->save($_POST)){//成功
						$this->redirect('User/index',array(),1," ");
					}else{//失败
						echo "<script>alert('修改失败或未作任何修改')</script>";
						$this->redirect('User/index',array(),1," ");
					}
		}else{
			$reginfo=D('user')->where('id='.session('id'))->find();
			$this->assign("reginfo",$reginfo);
			$this->display();
		}
	}
	//修改密码
	function changepwd(){
		$my=D('user')->where("id=".session('id'))->find();
//		var_dump($my);
		if($my['password']==$_POST['oripwd']){
			$db=new \Model\DbModel();	
			$res=$db->updatedata("user",array("password"=>$_POST['newpwd']),"id=".$my['id']);
			echo $res?"<script>alert('修改成功')</script>":"<script>alert('修改失败')</script>";
			//$this->redirect('User/index',array(),1," ");
		}else{
			echo "<script>alert('原密码错误')</script>";
		}
	}
	function changepwdbyajax($oripwd,$newpwd){
		$my=D('user')->where("id=".session('id'))->find();
//		var_dump($my);
		if($my['password']==$oripwd){
			$db=new \Model\DbModel();	
			$res=$db->updatedata("user",array("password"=>$newpwd),"id=".$my['id']);
			$res?$this->ajaxReturn(array("errorcode"=>0,"error"=>"修改成功！")):$this->ajaxReturn(array("errorcode"=>1,"error"=>"修改失败！"));
		}else{
			$this->ajaxReturn(array("errorcode"=>1,"error"=>"原密码错误！"));
		}
	}
	/*
	 * 微信登录，用户扫描二维码后的回调函数
	 * $_GET['state']是由登录页面的js通过当前时间戳与1~1000的随机数结合而成，
	 * 并在扫描登录成功后记录到数据库，以此来区分用户以及作为登录成功的标志
	 * */
	function wx_login(){
		if(!empty($_GET)){//
			var_dump($_GET);
			$html = file_get_contents("https://api.weixin.qq.com/sns/oauth2/access_token?appid=wx935cdb3a2a049e5c&secret=083e078b99a9b22e26d7d223ecd90c34&code=".$_GET['code']."&grant_type=authorization_code");
			$res=json_decode($html,true);
			$access_token=$res['access_token'];
			$openid=$res['openid'];
			//获取用户信息
			$htmlforuserinfo = file_get_contents("https://api.weixin.qq.com/sns/userinfo?access_token=".$access_token."&openid=".$openid."&lang=zh_CN");
			$user_res=json_decode($htmlforuserinfo,true);
			var_dump($user_res);
			$info=D('wx_user')->where("openid='".$user_res['openid']."'")->find();
			if($info){//存在表示不是第一次登录微信
				//修改该用户在数据库中的token，表示登录成功
				$db=new \Model\DbModel();
				$db->updatedata("wx_user",array("token"=>$_GET['state']),"openid='".$user_res['openid']."'");
			}else{
				//第一次登录，创建新的用户，与此微信的openid关联起来
				$id=D('user')->add(array("name"=>$user_res['nickname'],"touxiang"=>$user_res['headimgurl'],"password"=>"123456","status"=>"1","score"=>"999","create_time"=>$_SERVER['REQUEST_TIME']));
				$addres=D('wx_user')->add(array("user_id"=>$id,"openid"=>$user_res['openid'],"token"=>$_GET['state']));
				if($id&&$addres){
					session('id',$id);
				}
			}
		}
	}
	//登录页面通过ajax请求判断用户是否已经微信登录
	function whether_wx_login($token){
		$wx_user=D('wx_user')->where("token=".$token)->find();
		if($wx_user)
		$this->ajaxReturn($wx_user['user_id']);
	}
	//微信登录成功，刷新电脑端页面
	public function had_wx_login($id){
		$info=D('user')->where("id=".$id)->find();
			if($info){
				if($info['status']==1){//判断账号是否被冻结
					//echo "<script>alert('登录成功！')</script>";
					//给用户信息session持久化操作
					session('name',$info['name']);
					session('id',$info['id']);
					//允许登录，返回结果让电脑端页面跳转到个人中心
					$this->ajaxReturn(array("error"=>1,"tip"=>"登录成功！"));
				}else{
					$this->ajaxReturn(array("error"=>0,"tip"=>"账号已被冻结！"));
				}
			}
    }
}